import { ref, computed } from 'vue';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import katex from 'katex';
// 暂时注释掉插件导入以确保页面正常显示
import markdownItKatex from 'markdown-it-katex';
import markdownItEmoji from 'markdown-it-emoji';
import mermaid from 'mermaid';
import 'katex/dist/katex.min.css';

export function useMarkdown(options: any = {}) {
  const md = ref(new MarkdownIt({
    html: true,
    linkify: true,
    typographer: true,
    highlight: function (str, lang) {
      if (lang && hljs.getLanguage(lang)) {
        try {
          return hljs.highlight(str, { language: lang }).value;
        } catch (__) {}
      }
      return ''; // 使用外部默认转义
    },
    ...options
  }));

  // 添加数学公式支持 - 暂时禁用以确保页面正常显示
  md.value.use(markdownItKatex, {
    throwOnError: false,
    errorColor: '#cc0000'
  });

  // 添加emoji支持 - 暂时禁用以确保页面正常显示
  md.value.use(markdownItEmoji, {
    defs: {
      // 自定义emoji定义
    },
    shortcuts: {
      // 自定义快捷方式
      'angry': ['>:(', '>:-('],
      'blush': [':-)', ':)'],
      'broken_heart': ['</3', '<\x03'],
      'confused': [':-/', ':/'],
      'cry': [":'(", ":'-("]
    }
  });

  // 初始化mermaid
  mermaid.initialize({
    startOnLoad: false,
    theme: 'default',
    securityLevel: 'loose',
    fontFamily: 'monospace'
  });

  const render = (content: string) => {
    if (!content) return '';
    
    try {
      let html = md.value.render(content);
      
      // 处理mermaid图表
      html = html.replace(/<pre><code class="language-mermaid">(.*?)<\/code><\/pre>/gs, (match, code) => {
        const id = `mermaid-${Math.random().toString(36).substr(2, 9)}`;
        return `<div class="mermaid-container"><div id="${id}" class="mermaid">${code.trim()}</div></div>`;
      });
      
      return html;
    } catch (error) {
      console.error('Markdown渲染错误:', error);
      return `<p style="color: red;">渲染错误: ${error}</p>`;
    }
  };
  
  // 渲染mermaid图表
  const renderMermaid = async () => {
    try {
      const mermaidElements = document.querySelectorAll('.mermaid');
      for (const element of mermaidElements) {
        if (element.getAttribute('data-processed') !== 'true') {
          const id = element.id;
          const code = element.textContent || '';
          
          try {
            const { svg } = await mermaid.render(id + '_svg', code);
            element.innerHTML = svg;
            element.setAttribute('data-processed', 'true');
          } catch (error) {
            console.error('Mermaid渲染错误:', error);
            element.innerHTML = `<p style="color: red;">图表渲染错误: ${error}</p>`;
            element.setAttribute('data-processed', 'true');
          }
        }
      }
    } catch (error) {
      console.error('Mermaid初始化错误:', error);
    }
  };

  const renderInline = (content: string) => {
    if (!content) return '';
    return md.value.renderInline(content);
  };

  const registerPlugin = (plugin: any, options: any = {}) => {
    md.value.use(plugin, options);
  };

  return {
    md,
    render,
    renderInline,
    renderMermaid,
    registerPlugin
  };
}